<template>
  <div class="blog-detail">
    <a-button type="text" class="back-btn" @click="$router.go(-1)">
      < 返回文章列表
    </a-button>
    
    <div class="blog-content">
      <a-spin v-if="loading" size="large" />
      <template v-else>
        <h1>{{ blog_data.title }}</h1>
        
        <div class="blog-meta">
          <!-- <a-avatar :size="50" :src="blog_data.author.avatar" /> -->
          <UserAvatarCard
            :avatar="blog_data.author.avatar"
            :username="blog_data.author.name"
            :email="blog_data.author.email"
            />
          <div class="meta-info">
            <span class="author">{{ blog_data.author.name }}</span>
            <span class="date">{{ blog_data.date }}</span>
          </div>
        </div>
        
        <div class="blog-body">
          <div v-if="!blog_data.content" style="color: red">
            警告：文章内容为空
          </div>
          <div 
            v-else
            v-html="renderedMarkdown"
            style="border: 1px solid #eee; padding: 10px;"
          />
        </div>
        
        <div class="interaction-section">
          <div class="like-section">
            <a-button 
              type="primary" 
              shape="round"
              @click="handleLike"
              :icon="h(LikeOutlined)"
              :disabled="isLiked"
              :class="{ 'liked': isLiked }"
            >
              {{ likeCount }} 点赞
            </a-button>
          </div>

          <div class="comment-section">
            <CommentList :comments="comments" :fetch-sub-comments="fetchSubComments" @submit-reply="submitReply" />
            <a
                v-if="isMore"
                @click="loadMoreComments"
                class="load-more-comments"
                >
                获取更多评论
            </a>
            <a-form :model="commentForm" @finish="submitComment">
              <a-form-item>
                <a-textarea 
                  v-model:value="commentForm.content"
                  :rows="4"
                  placeholder="写下你的评论..."
                />
              </a-form-item>
              <a-form-item>
                <a-button 
                  html-type="submit" 
                  type="primary"
                  :disabled="!commentForm.content.trim()"
                >
                  发表评论
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBlogStore } from '@/stores/blog'
import MarkdownIt from 'markdown-it'
import { message } from 'ant-design-vue'
import hljs from 'highlight.js'
import { LikeOutlined } from '@ant-design/icons-vue'
import CommentList from '@/components/CommentList.vue'
import UserAvatarCard from '@/components/UserAvatarCard.vue'

export default {
  name: 'BlogDetailView',
  components: { 
    CommentList,
    UserAvatarCard
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true,
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(str, { language: lang }).value
          } catch (__) {}
        }
        return ''
      }
    })

    const blogStore = useBlogStore()
    const loading = ref(true)
    const commentForm = ref({
      content: ''
    })
    
    const blog_data = computed(() => blogStore.currentBlog)
    const likeCount = computed(() => blog_data.value?.likes || 0)
    const comments = computed(() => blog_data.value?.comments || [])
    const isLiked = computed(() => blogStore.isBlogLiked(blog_data.value?.id))
    
    const commentsPage = ref(1)
    const commentsTotal = ref( 0)
    const pageSize = 10 // 评论每一页的条数
    const isMore = computed(() => comments.value.length < commentsTotal.value)

    const fetchBlogDetail = async (id,page = 1,pagesize = 10) => {
      loading.value = true
      try {
        await blogStore.fetchBlogDetail(id,page,pagesize)
        commentsTotal.value = blogStore.currentBlog.comment_total
      } catch (error) {
        console.error('加载博客失败:', error)
        message.error('加载博客详情失败')
      } finally {
        loading.value = false
      }
    }
    
    const fetchTopComments = async (page = 1) => {
        const { list, total } = await fetchSubComments(null, page)
        console.log(list)
        console.log(total)
        blogStore.currentBlog.comments = [...blogStore.currentBlog.comments, ...list]
        commentsTotal.value = total
        commentsPage.value = page
    }
    const renderedMarkdown = computed(() => {
        return md.render(blog_data.value?.content || '')
    })

    const loadMoreComments = () => {
      fetchTopComments(commentsPage.value + 1)
    }

    onMounted(() => {
      const id = route.params.id
      if (id) {
        fetchBlogDetail(id,1,pageSize)
      } else {
        console.error('Missing blog ID in route parameters')
        router.push('/blogs')
      }
    })

    const handleLike = async () => {
      try{
        const success = await blogStore.likeBlog(blog_data.value.id)
        if (success) {
          message.success('点赞成功')
        }
      }catch(error) {
        message.error(error)
      }
    }

    const submitReply = async ({ comment, content }) => {
      
        try {
            const result = await blogStore.addComment(blog_data.value.id, content, comment.id)
            console.log("submitReply",result)
            if (result && result.comment) {
              if (!comment.children) comment.children = []
              comment.children.unshift({
                  ...result.comment,
                  author: {
                    id: result.comment.author.id || result.comment.author.getEmail?.(),
                    name: result.comment.author.name || result.comment.author.getName?.(),
                    avatar: result.comment.author.avatar || result.comment.author.getAvatar?.()
                  },
                  children: [],
                  comment_total: 0,
                  childrenLoaded: 0,
                  childrenPage: 1
              })
              comment.childrenLoaded = (comment.childrenLoaded || 0) + 1
              comment.comment_total = (comment.comment_total || 0) + 1
            }
        } catch (error) {
            console.error('Reply failed:', error)
            message.error('回复失败')
        }
    }
    
    const submitComment = async () => {
        if (commentForm.value.content.trim()) {
            try {
                console.log("submit comment");
                const result = await blogStore.addComment(blog_data.value.id, commentForm.value.content)
                if (result && result.comment) {
                    commentsTotal.value += 1
                    console.log("result comment :",result.comment);
                }
                commentForm.value.content = ''
            } catch (error) {
                message.error('评论失败')
            }
        }
    }

    const fetchSubComments = async (parentId, page = 1) =>{
        try {
            const { list , total } = await blogStore.fetchSubComments(blog_data.value.id, parentId, page, pageSize);
            return { list , total }
        } catch (error) {
            message.error('获取失败',error)
            return {
                list :[],
                total: 0
            }
        }
    }

    return {
      blog_data,
      loading,
      likeCount,
      isLiked,
      comments,
      commentForm,
      renderedMarkdown,
      handleLike,
      submitComment,
      h,
      LikeOutlined,
      submitReply,
      fetchSubComments,
      fetchTopComments,
      loadMoreComments,
      isMore
    }
  }
}
</script>

<style scoped>
.blog-detail {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.back-btn {
  margin-bottom: 20px;
}

.blog-content h1 {
  margin-bottom: 20px;
}

.blog-meta {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.meta-info {
  margin-left: 15px;
  display: flex;
  flex-direction: column;
}

.author {
  font-weight: bold;
  font-size: 1.1em;
}

.date {
  color: #666;
  font-size: 0.9em;
}

.blog-body {
  line-height: 1.8;
  font-size: 1.1em;
}

.interaction-section {
  margin-top: 40px;
}

.like-section {
  margin-bottom: 30px;
  text-align: center;
}

.like-section .ant-btn {
  padding: 0 25px;
  height: 40px;
  font-size: 16px;
  transition: all 0.3s;
}

.like-section .ant-btn.liked {
  background-color: #d9d9d9;
  border-color: #d9d9d9;
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}

.comment-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.comment-content {
  background-color: #fafafa;
  padding: 12px;
  border-radius: 4px;
}

.load-more-comments {
  display: block;
  text-align: center;
  margin: 16px auto;
  padding: 8px 0;
}
</style>
